package com.homework.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.homework.entity.Post;
import com.homework.service.PostService;
import com.homework.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

@Slf4j
public class PostClickInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    PostService postService;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        log.info("拦截url的链接----------->{}", request.getServletPath());
        String postId = request.getServletPath().substring("/post/".length());

        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        boolean isMatch = pattern.matcher(postId).matches();

        log.info("是否匹配成功 ----> {}", isMatch);

        if (!isMatch)
            return;

        boolean isExist = redisUtil.hHasKey("rank_post_" + postId, "post:viewCount");
        if (!isExist) {
            Post post = postService.getOne(new QueryWrapper<Post>().eq("id", postId).select(" id, view_count "));
            log.info("----->" + post.toString());

            // 注意加一
            redisUtil.hincr("rank_post_" + postId, "post:viewCount", post.getViewCount() + 1);
        } else {

            // 缓存阅读加一
            redisUtil.hincr("rank_post_" + postId, "post:viewCount", 1);
        }


        //tips 数据库阅读与缓存的阅读用定时器来同步
    }
}
